(function () {
    var pages = {};
    $.fn.urlAjax = function () {
        $(this).filter(function () {
            return !$(this).data('ajax');
        }).data('ajax', true).click(function (e) {
            if (!window.zlin.isAjaxLoad) {
                location.href = $(this).attr('href');
                return stopEvent(e);
            }
            var href = $(this).attr('href') || $(this).attr('action');
            if (!href) return stopEvent(e);
            var target = $(this).attr('target');
            loadTarget(href, target, {zhis: $(this)});
            return stopEvent(e);
        });
    };
    function loadTarget(href, target, options) {
        pages[href] = {url: href, target: target};
        $.ajax({
            url: href,
            dataType: "html",
            success: function (d) {
                var title = d.match(/<title>.*<\/title>/);
                if (!!title && title.length > 0) {
                    title = $(title[0]).text();
                    if (!!title)document.title = title;
                }
                if (!!options) {
                    var state = {
                        title: title,
                        url: href,
                        target: target
                    };
                    if (!!window.history && window.history.pushState)window.history.pushState(state, title, href);
                }
                $(target).html($(d).find(target).children().initialize());
                $(document).triggerHandler("url_ajax", [href]);
                $(document).scrollTo(0);
            },
            error: function (XMLResponse) {
                if (!!console)console.log(XMLResponse.responseText)
            }
        });
    }

    window.onpopstate = function (e) {
        if (!!e.state && e.state.url) {
            loadTarget(e.state.url, e.state.target);
        }
    }
})();